// 封装cartStore
import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { getUse } from './user.js'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart.js'
export const useCartStore = defineStore('cart', () => {
  const useCart = getUse()
  // console.log(useCart.getUseStore.token);
  const isLogin = computed(() => useCart.getUseStore.token)

  //刷新购物车列表函数方法
  const getNewCart = async () => {
    const res = await findNewCartListAPI()
    // console.log(res.result);
    cartList.value = res.result
  }
  // 定义state
  const cartList = ref([])
  // 定义添加购物车方法
  const cartStore = async (goods) => {
    console.log(cartList)
    const { skuId, count } = goods
    if (isLogin.value) {
      // 登录
      await insertCartAPI({ skuId, count })
      getNewCart()
    } else {
      // 本地登录
      // 通过匹配传递过来的商品对象中的skuId能不能在cartList 中找到，找到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      // 添加过
      if (item) {
        // 代表已经找到
        item.count++
      } else {
        // 没添加过
        cartList.value.push(goods)
      }
    }


  }
  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      getNewCart()
    } else {
      // 1.splice 找到要删除的下标
      // 2.filter
      const idx = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idx, 1)
    }

  }
  // 清空购物车
  const clearCartList = () => {
    cartList.value = []
  }
  // 单选框
  const changeCheck = (skuId, selected) => {
    // 通过skuId 找到要修改的那一项，然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }
  // 全选框
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }
  // 计算属性
  // 1.总的数量
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 2.总价
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  // 3.选框
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  // 4.已选商品
  const selectCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  // 5.总钱
  const selectPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
  return {

    cartStore,
    delCart,
    changeCheck,
    allCheck,
    clearCartList,
    cartList,
    allCount,
    allPrice,
    isAll,
    selectCount,
    selectPrice,
    getNewCart

  }
}, {
  persist: true
})